<template>
    <div class="create-edit-modal-wrapper">
        <el-dialog :model-value="props.value" :title="dialog.title" :width="dialog.width" destroy-on-close>
            <el-form ref="ruleFormRef" :model="formData" :rules="ruleForm" label-width="120px">
                <template v-if="dialog.detail?.triggerType == 'TIMER'">
                    <el-form-item label="触发表达式" style="width: 100%; margin-left: 0" prop="crontab">
                        <el-input
                            v-model="formData.crontab"
                            type="textarea"
                            show-word-limit
                            placeholder="请输入触发表达式"
                        />
                    </el-form-item>
                    <el-form-item label="开始执行日期" prop="beginTime">
                        <el-date-picker
                            v-model="formData.beginTime"
                            type="date"
                            placeholder="请选择开始执行日期"
                            style="width: 100%"
                            value-format="YYYY-MM-DD 00:00:00"
                            :disabled-date="date => disabledDate('begin', date)"
                        />
                    </el-form-item>
                    <el-form-item label="结束执行日期" prop="endTime">
                        <el-date-picker
                            v-model="formData.endTime"
                            type="date"
                            placeholder="请选择结束执行日期"
                            style="width: 100%"
                            value-format="YYYY-MM-DD 00:00:00"
                            :disabled-date="date => disabledDate('end', date)"
                        />
                    </el-form-item>
                </template>
                <template v-if="dialog.detail?.triggerType !== 'EVENT'">
                    <el-form-item label="任务超时" prop="timeout">
                        <el-input-number
                            v-model="formData.timeout"
                            :precision="0"
                            style="width: 100%"
                            align="left"
                            controls-position="right"
                            placeholder="请输入任务超时"
                        >
                            <template #suffix>
                                <span>秒</span>
                            </template>
                        </el-input-number>
                    </el-form-item>
                    <el-form-item label="超时处理方式" prop="timeoutMethod">
                        <el-select v-model="formData.timeoutMethod" placeholder="请选择触发方式" clearable disabled>
                            <el-option v-for="(value, key) in TimeoutMethod" :label="value" :key="key" :value="key" />
                        </el-select>
                    </el-form-item>
                </template>
                <el-form-item label="记录日志" prop="logRecord">
                    <el-switch v-model="formData.logRecord" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="props.close">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import { IoTTaskService } from '@great/services';
import { reactive, ref } from 'vue';
import type { PopupBoxProps } from '@great/utils';
import { useRequest } from 'vue-request';

interface IProps extends PopupBoxProps {
    row: Record<string, any>;
    callBack?: () => Promise<void>;
}
interface Dialog {
    title: string;
    width: number;
    detail?: Record<string, any>;
}
enum TimeoutMethod {
    failed = '设置执行结果为失败'
}

const props = defineProps<IProps>();
const dialog = reactive<Dialog>({
    title: '任务设置',
    width: 900,
    detail: undefined
});

const formData = reactive<Record<string, any>>({
    beginTime: '',
    endTime: '',
    crontab: '',
    timeout: null,
    timeoutMethod: '',
    logRecord: ''
});
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<FormRules<any>>({
    beginTime: [{ required: true, message: '请选择开始执行日期', trigger: ['blur', 'change'] }],
    endTime: [{ required: true, message: '请选择结束执行日期', trigger: ['blur', 'change'] }],
    crontab: [{ required: true, message: '请输入触发表达式', trigger: ['blur', 'change'] }],
    timeout: [{ required: true, message: '请输入任务超时', trigger: ['blur', 'change'] }],
    timeoutMethod: [{ required: true, message: '请选择超时处理方式', trigger: ['blur', 'change'] }],
    logRecord: [{ required: true, message: '请选择记录日志', trigger: ['blur', 'change'] }]
});

// 时间限制
const disabledDate = (type: string, date: Date): boolean => {
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0); // 重置 时间的小时、分钟、秒、毫秒
    if (date.getTime() < todayStart.getTime()) return true;
    let isDis = false;
    if (type == 'begin') {
        if (formData.endTime) {
            isDis = date.getTime() > new Date(formData.endTime).getTime();
        }
    } else {
        if (formData.beginTime) {
            isDis = date.getTime() < new Date(formData.beginTime).getTime();
        }
    }
    return isDis;
};

// 提交接口请求
const { run, loading } = useRequest(
    () => {
        return IoTTaskService.triggerJob(formData, props.row.jobNo);
    },
    {
        manual: true,
        onSuccess() {
            ElNotification({
                title: '设置成功！',
                type: 'success'
            });
            closeDialog();
        }
    }
);
// 表单提交
const submitForm = () => {
    ruleFormRef.value?.validate(valid => {
        valid && run();
    });
};

//关闭弹框
const closeDialog = () => {
    props.close();
    props.callBack?.();
};
// 获取详情
const getDetail = async () => {
    const res = await IoTTaskService.getDetail(props.row.jobNo);
    dialog.detail = res.data;
    Object.keys(formData).forEach(key => {
        formData[key] = res.data?.triggerModel[key];
    });
};

const init = () => {
    getDetail();
};
init();
</script>
<style scoped lang="scss">
.create-edit-modal-wrapper {
    .el-form {
        display: flex;
        flex-wrap: wrap;
        .el-form-item {
            width: calc((100% - 10px) / 2);
        }
        .el-form-item:nth-child(even) {
            margin-left: 10px;
        }
        :deep(.protocol-box) {
            .el-form-item__content {
                display: flex;
                .el-select {
                    flex: 1;
                }
                .el-select + .el-select {
                    margin-left: 10px;
                }
            }
        }
    }
}
</style>
